"use client";

import React, { useEffect } from "react";
import { Refine } from "@refinedev/core";
import routerProvider from "@refinedev/nextjs-router";
import { useNotificationProvider } from "@refinedev/antd";
import { dataProvider } from "@providers/data-provider";
import { authProviderClient } from "@providers/auth-provider/auth-provider.client";
import { useUserStore, useResourcesStore, useInitApp } from "@store";
import {Loading} from "@components/loading";

export default function RefineApp({ children }: { children: React.ReactNode }) {
  // 初始化应用状态
  useInitApp();
  const { token, isLogin } = useUserStore();
  const { resources, loading, loadResources } = useResourcesStore();

  // 当用户登录状态变化时，重新获取菜单资源
  useEffect(() => {
    if (token && isLogin) {
        loadResources();
    }
  }, [token, isLogin, loadResources]);

  if (loading) {
    return (
      <Loading/>
    );
  }

  return (
    <Refine
      routerProvider={routerProvider}
      dataProvider={dataProvider}
      notificationProvider={useNotificationProvider}
      authProvider={authProviderClient}
      resources={resources}
      options={{
        syncWithLocation: true,
        warnWhenUnsavedChanges: true,
        useNewQueryKeys: true,
        projectId: "9QX9NP-g5lnc2-ehEove",
      }}
    >
      {children}
    </Refine>
  );
}
